上一篇介紹了delegate,這一篇使用delegate來傳值
先在StoryBoard放上兩個View Controller,A Controller放上Button跟TextField,B Controller放上Label,我們要把TextField輸入的文字傳到Label上
接著來看程式的部分
@IBOutlet weak var inputTextField: UITextField!
@IBAction func goToSecondVC(_ sender: UIButton) {
performSegue(withIdentifier: "goToSecond", sender: self)
}
首先把StoryBoard的TextField跟Button跟程式碼做連結
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let secondVC = segue.destination as? SecondViewController {
secondVC.text = inputTextField.text
}
}
覆寫prepare這個function for segue,設一個secondVC的常數,secondVC的Label Text會是TextField的input
var text: String?
@IBOutlet weak var centerLabel: UILabel!
設定一個text type是string。再把Lable跟程式碼做連結
override func viewDidLoad() {
super.viewDidLoad()
centerLabel.text = text
}
最後再viewDodLoad裡寫下Label.text要顯示什麼一般的傳值方法就完成了。
在第二頁面放上一個新的TextField跟Button
protocol SecondViewControllerDelegate {
func passData(text: String)
}
在SecondViewController先寫上protocol以及要實現的function
var delegate: SecondViewControllerDelegate?
設定有個optional property叫做delegate,他的type為secondviewcontrollerdelegate。
@IBAction func popToRoot(_ sender: Any) {
delegate?.passData(text: textField.text!)
navigationController?.popViewController(animated: true)
}
設定按下Button後delegate要執行的method,以及要回到上一頁
class ViewController: UIViewController, SecondViewControllerDelegate {
繼承SecondViewControllerDelegate這個Protocol
func passData(text: String) {
inputTextField.text = text
}
繼承Protocol後要實現的方法,讓TextField的Text等於上一頁的Text
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let secondVC = segue.destination as? SecondViewController {
secondVC.text = inputTextField.text
secondVC.delegate = self
}
}
最後記得一定要加上secondVC.delegate = self,如此一來。Delegate傳值就完成了